﻿using System.Xml.Serialization;
using T4UtilityBelt.Serializers;
using T4UtilityBelt.UxDesigns;

namespace T4UtilityBelt.DataDesigns
{
    public abstract class Parent : Property
    {
        protected Parent(string name, string toName)
            : base(EntityModel.OptionalKeyType, name, EntityModel.OptionalSecondaryKeyType)
        {
            ToName = toName;
        }

        protected Parent(string name, string toName, bool required)
            : base(required ? EntityModel.KeyType : EntityModel.OptionalKeyType, 
            name, 
            required, 
            required ? EntityModel.SecondaryKeyType : EntityModel.OptionalSecondaryKeyType)
        {
            ToName = toName;
        }
        
        [XmlAttributeAttribute]
        [XSpecifiedValue("IsToNameSpecified")]
        public string ToName { get; set; }

        public virtual bool IsToNameSpecified
        {
            get { return true; }
        }

        private string _association;
        [XSpecifiedValue("IsAssociationSpecified")]
        public string Association
        {
            get
            {
                if (string.IsNullOrEmpty(_association))
                {
                    return ToName;
                }
                return _association;
            }
            set { _association = value; }
        }

        public bool IsAssociationSpecified
        {
            get { return Association != Name; }
        }

        [XIgnore]
        public Entity ToEntity { get; set; }

        [XmlAttribute]
        [XSpecifiedValue("IsMultiplicitySpecified")]
        public Multiplicity Multiplicity { get; set; }

        [XIgnore]
        public virtual bool IsMultiplicitySpecified
        {
            get { return true; }
        }

        internal override void FixModel(EntityModel model, Entity entity)
        {
            base.FixModel(model, entity);

            ToEntity = model.GetEntity(ToName);
            if (ToEntity == null)
            {
                throw new RenderException(string.Format("ToEntity not found: {0}", ToName));
            }
        }
    }
}